package com.hh.base.generator.database;

import com.hh.base.common.FiledBean;
import com.hh.base.common.TableBean;

import java.util.List;

/**
 * Created by liuhanhui on 2017/10/27.
 */
public class MysqlSQLGenerator extends SQLGenerator {

    public String tableCreateSQL(TableBean tableBean) {
        StringBuilder sb = new StringBuilder("");
        String primaryKey = " PRIMARY KEY (";
        sb.append("CREATE TABLE `" + tableBean.getName() + "`");
        sb.append("(\n");
        List<FiledBean> filedBeanList = tableBean.getFiledBeanList();
        for (FiledBean filedBean :
                filedBeanList) {
            sb.append("\t`" + filedBean.getName() + "` " + filedBean.getType() + "(" + filedBean.getLength() + ")");
            if (filedBean.getIsAutoIncrement() == 1) {
                sb.append(" NOT NULL ");
            } else {
                sb.append(" DEFAULT NULL ");
            }
            if (filedBean.getIsPrimary() == 1) {
                primaryKey = primaryKey + "`" + filedBean.getName() + "`,";
            }

            sb.append(" COMMENT '" + filedBean.getComment() + "',\n");
        }
        if (primaryKey.contains("`")) {
            return sb.append(primaryKey.substring(0, primaryKey.length() - 1) + ")").append("\n)").toString();
        } else {
            return sb.substring(0, sb.length() - 2) + "\n)";
        }
    }
}
